package com.ldatum.crm.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class ColumnUtil {
	/**
	 * 根据表名得到字段名并返回
	 * @param tableName
	 * @return
	 * @throws Exception
	 */
	public static List<String> GetColumnName(String tableName) throws Exception{
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSetMetaData rsmd = null;
		List<String> columns = new ArrayList<String>();
		try {
			con = DBUtil.open();
			String sql = "select * from "+tableName;
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			rsmd = rs.getMetaData();
			int counts = rsmd.getColumnCount();
			int i = 1;
			while(true){
				columns.add(rsmd.getColumnName(i++));
				if(i==counts+1){
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw (e);
		}
		return columns;
	}
	/**
	 * 根据表名得到表中个字段的数据类型
	 * @param tableName
	 * @return
	 * @throws Exception
	 */
	public static List<String> GetColumnType(String tableName) throws Exception{
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		ResultSetMetaData rsmd = null;
		List<String> types = new ArrayList<String>();
		try {
			con = DBUtil.open();
			String sql = "select * from "+tableName;
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			rsmd = rs.getMetaData();
			int counts = rsmd.getColumnCount();
			int i = 1;
			while(true){
				String type = rsmd.getColumnTypeName(i++);
				types.add(type.toLowerCase());
				if(i==counts+1){
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw (e);
		}
		return types;
	}
}
